
package com.v1.video.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.huawei.hwid.openapi.OpenHwID;
import com.huawei.hwid.openapi.out.IHwIDCallBack;
import com.iss.view.common.ToastAlone;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.domain.BindInfo;
import com.v1.video.domain.HuaWeiInfo;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.LoginUserInfoEntity;
import com.v1.video.domain.MainPageUploadEntity;
import com.v1.video.domain.UserInfo4_4;
import com.v1.video.domain.WeiXinPageInfo;
import com.v1.video.engine.NetEngine;
import com.v1.video.engine.RequestEngine;
import com.v1.video.exception.NetException;
import com.v1.video.exception.ServicesException;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.ParamList;
import com.v1.video.httpmanager.ParamList.Parameter;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.pay.MD5;
import com.v1.video.util.Logger;
import com.v1.video.util.Util;
import com.v1.video.util.Utility;
import com.v1.video.util.Utils;

import org.json.JSONException;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * 
 */
public class SettingLoginActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = "SettingLoginActivity";
	private static final int LOGIN_SSO = 1000;
	private static final int LOGIN_SSO_FAIL = 1001;
	private static final int LOGIN_SSO_CANCEL = 1002;
	private static final int LOGIN_COMMON = 1003;
	private static final int LOGIN_FAIL = 1005;
	private static final int LOGIN_SSO_SUCCESS = 1009;
	private static final int FINISH_LOAD_STAR_USERINFO = 1010;
    private ImageView back_Button;
//	private Button button_Browse;
	private Button button_Login;
    private TextView textView_forget;
    private TextView register;
    private ImageView ll_sina;
    private ImageView ll_qq;
    private ImageView ll_weixin;
    private TextView txtTitle;
    private ImageView imgIconUserName = null;
    private ImageView imgIconPwd = null;
    
    /** 前一个activity标识   0:app启动、 3:设置里的消息里的评论/关注; 2:设置里的搜索里的拍客,4零流量看头条，系统设置页,搜索用户 5,搜索拍客点击登录的返回,6首页关注,7首页我的*/
    private int loginFlag;
    private IWXAPI api;
    public static SettingLoginActivity loginActivity = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ShareSDK.initSDK(this);
        setContentView(R.layout.activity_setting_login);
        loginActivity = this;
    }

    @Override
    public void onBackPressed() {
    	// TODO Auto-generated method stub
    	super.onBackPressed();
    	finish();
    }
    
    @Override
    protected void initView() {
    	
//    	back_Button = (ImageView)findViewById(R.id.iv_result);
//    	button_Browse = (Button)findViewById(R.id.btn_browse);
        editText_username = (EditText)findViewById(R.id.editText_username);
        editText_password = (EditText)findViewById(R.id.editText_password);
        button_Login = (Button)findViewById(R.id.button_login);
        textView_forget = (TextView)findViewById(R.id.textView_forget);
        register = (TextView)findViewById(R.id.textView_register);
        ll_sina =(ImageView)findViewById(R.id.layout_sina);
        ll_qq =(ImageView)findViewById(R.id.login_btn_qq);
        ll_weixin =(ImageView)findViewById(R.id.login_btn_weixin);
        imgIconUserName = (ImageView)findViewById(R.id.login_img_username_icon);
        imgIconPwd = (ImageView)findViewById(R.id.login_img_pwd_icon);
        txtTitle = (TextView)findViewById(R.id.tv_title);
        findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });
		String channelId = Util.getChanelId(this);
		if (!TextUtils.isEmpty(channelId) && "100019".equals(channelId)) {
			ImageView mIvHuaWei=(ImageView)findViewById(R.id.iv_huawei);
			mIvHuaWei.setVisibility(View.VISIBLE);
			mIvHuaWei.setOnClickListener(this);
			
			Bundle bundle = new Bundle();
	        bundle.putString("gameSubAcctBtn", "0");//缺省为0     是否显示“切换子帐号”按钮
	        bundle.putBoolean("useSMSLogin", false);//缺省为true，是否使用短信快登。
	        bundle.putInt("getNickName", 1);//是否优先返回昵称 0否（缺省）  1是
	        
			OpenHwID.setLoginProxy(this, Constant.HUAWEI_APP_KEY, new IHwIDCallBack() {
				@SuppressWarnings({ "rawtypes", "unchecked" })
				@Override
				public void onUserInfo(HashMap map) {
	                Logger.d("SettingLoginActivity", "onUserInfo:" + map);
					updateInfo(map);
				}
			}, bundle);
		}
    }

    @Override
    protected void initData() {
        String agreementStr = getString(R.string.setting_login_agreement2);
        setAgreementText(agreementStr,13,agreementStr.length());
//        textView_forget.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        
        Intent intent = getIntent();
        loginFlag = intent.getIntExtra("loginFlag", 0);   
        
        txtTitle.setText(getResources().getString(R.string.login_account_login_label));
        api = WXAPIFactory.createWXAPI(this, Constant.APP_ID);
        api.registerApp(Constant.APP_ID);  
        button_Login.setEnabled(false);
        imgIconPwd.setEnabled(false);
    }

    @Override
    protected void setListener() {
    	
//    	back_Button.setOnClickListener(this);
//    	button_Browse.setOnClickListener(this);
        editText_username.setOnClickListener(this);
        editText_username.setLongClickable(false);
        editText_username.setTextIsSelectable(false);
        editText_password.setOnClickListener(this);
        editText_password.setLongClickable(false);
        editText_password.setTextIsSelectable(false);
        button_Login.setOnClickListener(this);
        textView_forget.setOnClickListener(this);
        register.setOnClickListener(this);
        ll_sina.setOnClickListener(this);
        ll_qq.setOnClickListener(this);
        ll_weixin.setOnClickListener(this);
//        button_Login.setOnTouchListener(new OnTouchListener() {
//			
//			@Override
//			public boolean onTouch(View arg0, MotionEvent arg1) {
//				// TODO Auto-generated method stub
//				button_Login.setTextColor(SettingLoginActivity.this.getResources().getColor(R.color.white));
//				return false;
//			}
//		});
//        button_Login.setOnFocusChangeListener(new OnFocusChangeListener() {
//			
//			@Override
//			public void onFocusChange(View arg0, boolean arg1) {
//				// TODO Auto-generated method stub
//				if(arg1){
//					button_Login.setTextColor(SettingLoginActivity.this.getResources().getColor(R.color.white));
//				}else{
//					button_Login.setTextColor(SettingLoginActivity.this.getResources().getColor(R.color.headline_blue));
//				}
//			}
//		});
        editText_username.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if(hasFocus){
					imgIconUserName.setEnabled(true);
				}else{
					imgIconUserName.setEnabled(false);
				}
			}
		});
        editText_password.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if(hasFocus){
					imgIconPwd.setEnabled(true);
				}else{
					imgIconPwd.setEnabled(false);
				}
			}
		});
        editText_username.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				int lenghtUserName = editText_username.getText().toString().length();
				int lengthPwd = editText_password.getText().toString().length();
				if(lengthPwd <=0 || lenghtUserName <= 0){
					button_Login.setEnabled(false);
				}else{
					button_Login.setEnabled(true);
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
        editText_password.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				int lenghtUserName = editText_username.getText().toString().length();
				int lengthPwd = editText_password.getText().toString().length();
				if(lengthPwd <=0 || lenghtUserName <= 0){
					button_Login.setEnabled(false);
				}else{
					button_Login.setEnabled(true);
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
    }
    
    private void setAgreementText(String str,int start,int end){
//        SpannableString sp=new SpannableString(str); 
//        sp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.setting_login_text_link)),start,end,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
////        sp.setSpan(new NolineClickableSpan() {
////            
////            @Override
////            public void onClick(View widget) {
////                ToastAlone.showToast(SettingLoginActivity.this, "最终协议", Toast.LENGTH_SHORT);
////            }
////        }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        textView_agreement.setText(sp);
////        textView_agreement.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textView_register:
                Intent intent_register = new Intent(this,UserRegisterActivity.class);
                startActivity(intent_register);
                break;
            case R.id.button_login:
            	login();
                break;
            case R.id.layout_sina:
//            	Intent intent_sina = new Intent(SettingLoginActivity.this,SinaLoginActivity.class);
//            	startActivity(intent_sina);
                sinaLogin();
                break;
            case R.id.login_btn_weixin:
            	weChatLogin();
            	break;
            case R.id.login_btn_qq:
            	qqLogin();
            	break;
            case R.id.textView_forget:
            	Intent intent_forget = new Intent(SettingLoginActivity.this,SettingForget1Activity.class);
            	startActivity(intent_forget);
            	break;
            case R.id.iv_huawei:
            	OpenHwID.login(new Bundle());
            	break;
        }

    }

    Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what){
				case LOGIN_COMMON:	//数据读取成功
					new AsyncLoadStarUserInfo().execute();
					isLoginSuccess = true;
//					if(checkLoginThread != null && checkLoginThread.isAlive()){
//						checkLoginThread.interrupt();
//						checkLoginThread = null;
//					}
					Logger.i(TAG, "登录成功了。。。。。");
					if(LoginInfo.getInstance().isLogin()){
						jumpTo();
					}
//					if(LoginInfo.getInstance().getCode()!= null && LoginInfo.getInstance().getCode().equals("1")){
//						//Toast.makeText(SettingLoginActivity.this, LoginInfo.getInstance().getMsg(), Toast.LENGTH_SHORT).show();
//						Logger.i("LoginInfo", "下面执行SettingLoginActivity方saveInstance2222222方法");
//						LoginInfo.getInstance().saveInstance(SettingLoginActivity.this);
//						jumpTo();
//					}
//					else{
//						Toast.makeText(SettingLoginActivity.this, LoginInfo.getInstance().getMsg(), Toast.LENGTH_SHORT).show();
//					}
					clearLoginDialog();
					break;
				case LOGIN_SSO_SUCCESS:
					new AsyncLoadStarUserInfo().execute();
					isLoginSuccess = true;
					if(LoginInfo.getInstance().isLogin()){
						jumpTo();
					}
					if(progDialog != null)
				        progDialog.dismiss();
				        progDialog = null;
					break;
				case 1://登录超时
					Toast.makeText(SettingLoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
//					if(loginThread.isAlive()){
//						loginThread.interrupt();
//						loginThread = null;
//					}
					clearLoginDialog();
					break;
				case LOGIN_FAIL:
					clearLoginDialog();
					break;
				case LOGIN_SSO:
					Logger.i(TAG, "第三方登录返回信息了，登录本服务器的接口");
					progDialog = Utils.getProgressDialog(SettingLoginActivity.this,"正在登录……");
			    	progDialog.show();
					Platform plat = (Platform) msg.obj;
					PlatformDb db = plat.getDb();
//					gotoLoginOfSSO(String nickname,String gender,String province,String city,String country,String picture,int type,String access_token,String openid){
					if(QQ.NAME.equals(db.getPlatformNname())){
//						engine.QQHuLianLoginSSO(SettingLoginActivity.this,db.getToken(), db.getExpiresIn(), db.getUserId(), "192.168.1.100", db.getExpiresTime(),db.getUserName(),db.getUserIcon());
						gotoLoginOfSSO(db.getUserName(),db.getUserGender(),"","","",db.getUserIcon(),2,db.getToken(),db.getUserId());
					}else if(SinaWeibo.NAME.equals(db.getPlatformNname())){
						gotoLoginOfSSO(db.getUserName(),db.getUserGender(),"","","",db.getUserIcon(),1,db.getToken(),db.getUserId());
					}
//                    new LoingSSOAsync((Platform) msg.obj).execute();
                    break;	
				case LOGIN_SSO_FAIL:
//					if(bindingPd != null && bindingPd.isShowing()){
//		                bindingPd.cancel();
//		            }.
					if(progDialog != null)
				        progDialog.dismiss();
				        progDialog = null;
					break;
				case FINISH_LOAD_STAR_USERINFO:
//					String str = "\"localCateGroup\"\\s*:\\s*{\\s*.*\\s*.*\\s*},\\s*";
					getTheStarUserInfoToServer((String)msg.obj);
					break;
			}
		}
    	
		
    };
    
    /**
	 * 业务自由逻辑，主要用获取到的用户信息
	 * @param map
	 */
	@SuppressWarnings("deprecation")
	private void updateInfo(HashMap<String, Object> map){
	    if(map!=null && map.get("userName")!=null && map.get("userID")!=null){
	    	HuaWeiInfo huaWeiInfo=new HuaWeiInfo();
	    	huaWeiInfo.setUserName(String.valueOf(map.get("userName")));
	    	huaWeiInfo.setUserID(String.valueOf(map.get("userID")));
	    	huaWeiInfo.setAccesstoken(URLEncoder.encode(String.valueOf(map.get("accesstoken"))));
			new LoingSSOAsync(Constant.SSO_LOGIN_HUAWEI, huaWeiInfo).execute();
	    }
	}
    
    private void jumpTo(){
    	
    	switch(loginFlag){
	    	case 0:
	    	case 1:
//	    		Intent intent = new Intent(SettingLoginActivity.this, HomepageActivity.class);
//				startActivity(intent);
//				finish();
	    		Intent mainMyPage1 = new Intent();
                mainMyPage1.setClass(SettingLoginActivity.this, MainPageNewActivity.class);                            
                setResult(RESULT_OK,mainMyPage1);    
                finish();
				break;
	    	case 2:// 2:设置里的搜索里的拍客,拍客，看透条登录完成之后直接返回
	    		Logger.i(TAG, "登录从这里返回");
                setResult(RESULT_OK, new Intent().putExtra("login", true));
                finish();
	    	case 4:// 4:设置里的零流量看头条、系统设置；
                finish();
	    	    break;
	    	case 5://设置里的消息里的评论/关注
                Logger.i("111", "这块执行，返回设置-消息-评论/关注");
//              SettingLoginActivity.this.setResult(RESULT_OK);
                Intent search = new Intent();
                search.setClass(SettingLoginActivity.this, OptionSearchActivity.class);                            
                setResult(RESULT_OK,search);                  
                finish();
                break;
	    	case 6://首页关注
                Intent mainAttentionPage = new Intent();
                mainAttentionPage.setClass(SettingLoginActivity.this, MainPageNewActivity.class);                            
                setResult(RESULT_OK,mainAttentionPage);                  
                finish();
                break;
	    	case 7://首页我的
                Intent mainMyPage = new Intent();
                mainMyPage.setClass(SettingLoginActivity.this, MainPageNewActivity.class);                            
                setResult(RESULT_OK,mainMyPage);                  
                finish();
                break;
		   /* case 100:// 跳转到圈子首页
				Intent quanzi = new Intent();
				quanzi.putExtra("showTab", V1QuanMainActivity.TAB_MY);
				quanzi.setClass(SettingLoginActivity.this, V1QuanMainActivity.class);
				setResult(RESULT_OK, quanzi);
				finish();
				break;*/
		    case 110:// 跳转到发布页
				Intent fabu = new Intent();
				fabu.putExtra("loginState", true);
				fabu.setClass(SettingLoginActivity.this, SaveShareActivity.class);
				setResult(RESULT_OK, fabu);
				finish();
				break;
		    case 130:// 跳转到发布页
				Intent shouye = new Intent();
				shouye.putExtra("loginState", true);
				shouye.setClass(SettingLoginActivity.this, MainPageNewActivity.class);
				setResult(RESULT_OK, shouye);
				finish();
				break;
    	}
        
    }
    
    //登录功能相关
    
    private EditText editText_username; 
    private EditText editText_password;
    
    private ProgressDialog progDialog;
    private Thread checkLoginThread;
    private Thread loginThread;
    
    private boolean isLoginSuccess;
    
    private void login(){
    	try{
        	String username = editText_username.getText().toString();
        	String password = editText_password.getText().toString();
        	
        	if(username == null || username.equals("")){
        		ToastAlone.showToast(SettingLoginActivity.this, "请输入手机号/用户名/邮箱", Toast.LENGTH_SHORT);
        		return;
        	}
        	if(password == null || password.equals("")){
        		ToastAlone.showToast(SettingLoginActivity.this, "请输入密码", Toast.LENGTH_SHORT);
        		return;
        	}
        	if(username.equals("")){
        		Logger.i(TAG, "用户名格式错误 11111111");
                Toast.makeText(this, "用户名格式错误", Toast.LENGTH_SHORT).show();
                return;
            }else{
                byte name[] = username.getBytes("GBK");
                if(name != null){
                    if(name.length < 4 || name.length > 20){
                    	Logger.i(TAG, "用户名格式错误 2222222222222");
                        Toast.makeText(this, "用户名格式错误", Toast.LENGTH_SHORT).show();
                        return; 
                    }
                }else{
                	Logger.i(TAG, "用户名格式错误 3333333333");
                    Toast.makeText(this, "用户名格式错误", Toast.LENGTH_SHORT).show();
                    return; 
                }
            }            
//            Pattern p = Pattern.compile("^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5@]+$");
        	Pattern p = Pattern.compile("^[a-zA-Z0-9_\u4e00-\u9fa5]+[a-zA-Z0-9_\u4e00-\u9fa5@.]+$");
            Matcher m = p.matcher(username);
            boolean b = m.matches();
            if (!b) {
            	Logger.i(TAG, "用户名格式错误 4444444444444444");
                Toast.makeText(this, "用户名格式错误", Toast.LENGTH_SHORT).show();
                return;
            }
    //    	Pattern p = Pattern.compile("^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$");
    //    	Matcher m = p.matcher(username);
    //    	boolean b = m.matches();
    //    	
    //    	if(username.length() < 4 ||
    //    			username.length() > 16||
    //    		!b
    //    			){
    //    		Toast.makeText(this, "用户名格式错误", Toast.LENGTH_SHORT).show();
    //    		return;
    //    	}
        	Pattern p2 = Pattern.compile("[_a-zA-Z][_a-zA-Z0-9]");
        	Matcher m2 = p2.matcher(password);
        	boolean b2 = m2.matches();
        	if(password.length() < 6 ||
        			password.length() > 20||
        		b2
        			){
        		Toast.makeText(this, "密码格式错误", Toast.LENGTH_SHORT).show();
        		return;
        	}
        	
        	if(!Utility.isConnected(SettingLoginActivity.this)){
        		Toast.makeText(this, "无网络连接，请检查网络设置", Toast.LENGTH_SHORT).show();
        		return;
        	}
        	RequestEngine request = new RequestEngine();
    		request.getLoginInfo(SettingLoginActivity.this, editText_username.getText().toString(), editText_password.getText().toString(),handler,LOGIN_COMMON,LOGIN_FAIL);
    		
//        	loginThread();
//        	checkLogin();
        	showLoginDialog();
    	}catch(Exception e){
            e.printStackTrace();
        }
    }
    
    private void loginThread(){
    	MobclickAgent.onEvent(SettingLoginActivity.this, "login_id");
    	isLoginSuccess = false;
    	
    	loginThread = new Thread(){
    		
    		public void run(){
    			
    			try {
					LoginInfo loginInfo = new NetEngine().getLoginInfo(SettingLoginActivity.this,editText_username.getText().toString(), editText_password.getText().toString());
//					if(loginInfo.getCode() != null && loginInfo.getCode().equals("0")){
//						
//						LoginInfo.getInstance().saveInstance(SettingLoginActivity.this);
////						loginInfo.saveInstance(SettingLoginActivity.this);
//					}
					Message msg = new Message();
					msg.what = LOGIN_COMMON;
					handler.sendMessage(msg);
				} catch (NetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			
    		}
    		
    	};
    	loginThread.start();
    	
    }
    
    private void checkLogin(){
    	
    	checkLoginThread = new Thread(){
    		
    		public void run(){
    			try {
					Thread.sleep(30000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			if(!isLoginSuccess){
					Message msg = new Message();
					msg.what = 1;
					handler.sendMessage(msg);
				}
    			
    		}
    		
    	};
    	checkLoginThread.start();
    	
    }
    
    private void showLoginDialog(){
    	
//    	back_Button.setEnabled(false);
//    	button_Browse.setEnabled(false);
        editText_username.setEnabled(false);
        editText_password.setEnabled(false);
        button_Login.setEnabled(false);
        textView_forget.setEnabled(false);
        register.setEnabled(false);
        ll_sina.setEnabled(false);
        ll_qq.setEnabled(false);
        ll_weixin.setEnabled(false);
    	progDialog = Utils.getProgressDialog(SettingLoginActivity.this,"正在登录……");
    	progDialog.show();
    }
    
    private void clearLoginDialog(){
    	
//    	back_Button.setEnabled(true);
//    	button_Browse.setEnabled(true);
        editText_username.setEnabled(true);
        editText_password.setEnabled(true);
        button_Login.setEnabled(true);
        textView_forget.setEnabled(true);
        register.setEnabled(true);
        ll_sina.setEnabled(true);
        ll_qq.setEnabled(true);
        ll_weixin.setEnabled(true);
        editText_password.setText("");
        if(progDialog != null)
        progDialog.dismiss();
        progDialog = null;
        
    }
    
    //第三方登录
    
    
    
//    public static WeiboAuth getmWeiboAuth() {
//    	if(mWeiboAuth == null){
//    		mWeiboAuth = new WeiboAuth(instance, Constant.APP_KEY, Constant.REDIRECT_URL, Constant.SCOPE);
//    	}
//		return mWeiboAuth;
//	}
//
//	private void initWeibo(){
//    	
//    }
    
    private void sinaLogin() {
    	MobclickAgent.onEvent(SettingLoginActivity.this, Constant.THIRDPARTY_SINAWEIBO_ID, "登录_"+SinaWeibo.NAME);
        thirdPartyLogin(ShareSDK.getPlatform(SettingLoginActivity.this, SinaWeibo.NAME));
    }
    
    private void qqLogin(){
    	MobclickAgent.onEvent(SettingLoginActivity.this, Constant.THIRDPARTY_QQ_ID, "登录_"+QQ.NAME);
    	thirdPartyLogin(ShareSDK.getPlatform(SettingLoginActivity.this, QQ.NAME));
    }
    
    private void weChatLogin(){
    	MobclickAgent.onEvent(SettingLoginActivity.this, Constant.THIRDPARTY_WEIXIN_ID, "登录_"+Wechat.NAME);
//    	thirdPartyLogin(ShareSDK.getPlatform(SettingLoginActivity.this, Wechat.NAME));
    	
    	if(api != null && api.isWXAppInstalled()){
    		thirdPartyLoginOfWeixin();
		}else{
			ToastAlone.showToast(SettingLoginActivity.this, "亲，您尚未安装微信客户端，请下载安装~", 1);
		}
    }
    
    private ProgressDialog bindingPd;
    
    private void thirdPartyLogin(Platform weibo) {
        bindingPd = Utils.getProgressDialog(SettingLoginActivity.this,"正在授权...", null);
        bindingPd.show();
        if(weibo.isValid()){
            weibo.removeAccount();
        }
//        if(weibo.getName().equals(TencentWeibo.NAME)){
//        	weibo.SSOSetting(true);
//        }
        weibo.setPlatformActionListener(new Listener());
        weibo.showUser(null);
        MobclickAgent.onEvent(SettingLoginActivity.this, "thirdLogin_id");
    }
    
    private void thirdPartyLoginOfWeixin() {
        bindingPd = Utils.getProgressDialog(SettingLoginActivity.this,"正在授权...", null);
        bindingPd.show();
        final SendAuth.Req req = new SendAuth.Req();
		req.scope = "snsapi_userinfo";		
		req.state = "none";
		api.sendReq(req);
		Constant.setLogin(true);
        MobclickAgent.onEvent(SettingLoginActivity.this, "thirdLogin_id");
    }
    
    GetWeixinDataWithToken tastGetWeixinToken;
    public void LoginProcessWeixin(int type,String token){
    	if(type == 0){
//    		Logger.i(TAG, "token="+token);    		
    		if(tastGetWeixinToken == null){
    			tastGetWeixinToken = new GetWeixinDataWithToken(token);
    			tastGetWeixinToken.execute();
    		}else{
    			tastGetWeixinToken = null;
    			tastGetWeixinToken = new GetWeixinDataWithToken(token);
    			tastGetWeixinToken.execute();
    		}
    	}
//    	if(type != 0){
    		if(bindingPd != null && bindingPd.isShowing()){
                bindingPd.cancel();
            }
//    	}
    	Constant.setLogin(false);
    }
    
    public class GetWeixinDataWithToken extends AsyncTask<Void, Void, Void> {
    	String token = "";
    	private String errorMsg;
    	private ProgressDialog pd;
    	WeiXinPageInfo pageInfo;
    	public GetWeixinDataWithToken(String token){
    		this.token = token;
    	}
    	
    	public GetWeixinDataWithToken(){
    	}    	
    	
    	@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pd = Utils.getProgressDialog(SettingLoginActivity.this,"正在获取授权信息", this);
			pd.show();
		}
    	
		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			try {
				NetEngine engine = new NetEngine();
				pageInfo = engine.getAccessToken(token);

			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = e.getMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (pd != null && pd.isShowing()) {
				pd.cancel();
			}
			if (TextUtils.isEmpty(errorMsg)) {
//				gotoLoginOfSSO(String nickname,String gender,String province,String city,String country,String picture,int type,String access_token,String openid){
//				loginInfo = engine.wechatLoginSSO(SettingLoginActivity.this,weiXinInfo.getAccess_token(), weiXinInfo.getExpires_in(),
//            			weiXinInfo.getOpenid(), "192.168.1.100", weiXinInfo.getExpires_in(),"1","1");
				gotoLoginOfSSO("","","","","","",3,pageInfo.getAccess_token(),pageInfo.getOpenid());
//				new LoingSSOAsync(Constant.SSO_LOGIN_WEIXIN, pageInfo).execute();
			}else{
				ToastAlone.showToast(SettingLoginActivity.this, errorMsg, 1);
			}
		}
		
    }
    
    private class Listener implements PlatformActionListener{

        @Override
        public void onError(Platform plat, int action, Throwable t) {
//            Logger.i("plat", "onerror action="+action);
            switch (action) {
                case Platform.ACTION_USER_INFOR:
                    if(bindingPd != null && bindingPd.isShowing()){
                        bindingPd.cancel();
                    }
                    plat.removeAccount();
                    Logger.i(TAG, "授权失败");
                    t.printStackTrace();
                    Logger.i(TAG, "t.printStackTrace()="+t.getMessage().toString());
                    ToastAlone.showToast(SettingLoginActivity.this, plat.getName()+"授权错误", 1);
                    
                    break;

            }
        }
        
        @Override
        public void onComplete(Platform plat, int action, HashMap<String, Object> arg2) {
//            Logger.i("plat", "oncomplete action="+action);
            switch (action) {
                case Platform.ACTION_USER_INFOR:
                    Message message = Message.obtain();
                    message.what = LOGIN_SSO;
                    message.obj = plat;                    
                    handler.sendMessage(message);
                    if(bindingPd != null && bindingPd.isShowing()){
                        bindingPd.cancel();
                    }
                    break;
                    
                    
            }
   
        }
        
        @Override
        public void onCancel(Platform plat, int action) {
//            Logger.i("plat", "oncancel action="+action);
            switch (action) {
                case Platform.ACTION_USER_INFOR:
                    if(bindingPd != null && bindingPd.isShowing()){
                        bindingPd.cancel();
                    }
                    ToastAlone.showToast(SettingLoginActivity.this, plat.getName()+"授权取消", 1);
                    plat.removeAccount();
                    
                    break;

            }
            
        }
    }
    
    /**
     * 
     * @param nickname
     * @param gender
     * @param province
     * @param city
     * @param country
     * @param picture
     * @param type
     * @param access_token
     * @param openid
     */
    private void gotoLoginOfSSO(String nickname,String gender,String province,String city,String country,String picture,int type,String access_token,String openid){
    	String key = Constant.getUserCheckKey(openid,access_token);
    	key = MD5.getMessageDigest(key);
    	String url = V1VideoHttpApi.GET_INFO_TO_LOGIN_SSO() + "&devid=" + Constant
				.DEVICEID+"&oauth_id="+type+"&access_token="+access_token+"&openid="+openid+"&key="+key;
    	
		Logger.i(TAG, "第三方登录Url =" + url);
		ParamList list = new ParamList();
		list.add(new Parameter("nickname", nickname));
		list.add(new Parameter("gender", gender));
		list.add(new Parameter("province", province));
		list.add(new Parameter("city", city));
		list.add(new Parameter("country", country));
		list.add(new Parameter("picture", picture));
		list.add(new Parameter("lastLoginIp", ""));
		list.add(new Parameter("longitude", ""));
		list.add(new Parameter("latitude", ""));
		list.add(new Parameter("baseStation", ""));
		list.add(new Parameter("cellIdentity", ""));
		list.add(new Parameter("IMEI", Constant.DEVICEID));
		list.add(new Parameter("IMSI", Utils.getSubscriberId(this)));
		Logger.i(TAG, "nickname="+nickname+"_gender="+gender+"_picture="+picture);
		RequestManager.getInstance().postRequest(SettingLoginActivity.this, url, list,
				LoginUserInfoEntity.class, 0, "SettingLoginActivity",
				new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String key) {
						// TODO Auto-generated method stub
						Logger.i(TAG, "onSuccess.object=" + object.toString());
						LoginInfo loginInfo = LoginInfo.getInstance();
						if (object != null) {
							LoginUserInfoEntity entity = (LoginUserInfoEntity) object;
							com.v1.video.domain.BaseEntity.Header header = entity
									.getHeader();
							if (header == null) {
								ToastAlone.showToast(SettingLoginActivity.this, "未知错误",
										Toast.LENGTH_SHORT);
								Message msg = handler.obtainMessage();
								msg.what = LOGIN_SSO_FAIL;
								handler.sendMessage(msg);
								return;
							} else if (!header.getStatus().equals("1")) {
								Message msg = handler.obtainMessage();
								msg.what = LOGIN_SSO_FAIL;
								handler.sendMessage(msg);
								ToastAlone.showToast(SettingLoginActivity.this,
										header.getMessage(), Toast.LENGTH_SHORT);
								return;
							} else if (header.getStatus().equals("1")) {
								if (entity.getBody() != null) {

									if (entity.getBody().getStatus()
											.equals("1")) {
										UserInfo4_4 userInfo = entity.getBody()
												.getData();
										loginInfo.setUserId(userInfo.getUid());
										loginInfo.setUserName(userInfo
												.getUsername());
										loginInfo.setLoginName(userInfo
												.getUsername());
										loginInfo.setNickName(userInfo
												.getNickname());
										loginInfo.setUserImg(userInfo
												.getPicture());
										loginInfo.setDetail(userInfo
												.getSignature());
										loginInfo.setSex(userInfo.getGender());
										loginInfo.setRegion(userInfo
												.getAddress());
										loginInfo.setState(userInfo.getStatus());
										loginInfo.setUserBackImg(userInfo
												.getBgpic());
										loginInfo.setUserIdOld(userInfo
												.getOld_uid());
										loginInfo.setIsCertification(userInfo
												.getIsauth());
										loginInfo.setTick(userInfo.getTick());
										Logger.i(TAG, "userInfo.getTick()=="+userInfo.getTick());
										loginInfo.setLogin(true);
										loginInfo
												.setLoginState(LoginInfo.LOGIN);
										loginInfo.setSetUserName(true);
										loginInfo.setToken(entity.getBody()
												.getToken());
										Logger.i(TAG, "登录解析方法");
										loginInfo.saveInstance(SettingLoginActivity.this);
										Message msg = handler.obtainMessage();
										msg.what = LOGIN_SSO_SUCCESS;
										handler.sendMessage(msg);
									} else {
										Message msg = handler.obtainMessage();
										msg.what = LOGIN_SSO_FAIL;
										handler.sendMessage(msg);
										ToastAlone.showToast(SettingLoginActivity.this, entity
												.getBody().getMessage(),
												Toast.LENGTH_SHORT);
									}

								} else {
									// toast(header.getMessage());
									Message msg = handler.obtainMessage();
									msg.what = LOGIN_SSO_FAIL;
									handler.sendMessage(msg);
								}
							} else {
								Message msg = handler.obtainMessage();
								msg.what = LOGIN_SSO_FAIL;
								handler.sendMessage(msg);
							}
						}

					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						Logger.i(TAG, message);
						Message msg = handler.obtainMessage();
						msg.what = LOGIN_SSO_FAIL;
						handler.sendMessage(msg);
					}
				});

		return;
    }

    /**
     * 授权之后传到服务器验证
     *
     */
    private class LoingSSOAsync extends AsyncTask<Void, Void, Void> {
        
        private Platform plat;
        private LoginInfo loginInfo;
        private String errorMsg;
        private ProgressDialog pd;
        int type = 0;
        WeiXinPageInfo weiXinInfo;
        private HuaWeiInfo mHuaWeiInfo;
        public LoingSSOAsync(Platform plat) {
            this.plat = plat;
        }
        public LoingSSOAsync(int type,WeiXinPageInfo weiXinInfo){
        	
        	this.type = type;
        	this.weiXinInfo = weiXinInfo;
        }
        public LoingSSOAsync(int type,HuaWeiInfo huaWeiInfo){
        	this.type = type;
        	this.mHuaWeiInfo = huaWeiInfo;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = Utils.getProgressDialog(SettingLoginActivity.this,"正在登录...", this);
            pd.show();            
        }
        
        @Override
        protected Void doInBackground(Void... params) {
            try {
                NetEngine engine = new NetEngine();
                if(type == 0){
	                PlatformDb db = plat.getDb();
	                Logger.i(TAG, "db.getPlatformNname()=="+db.getPlatformNname());
	                if(SinaWeibo.NAME.equals(db.getPlatformNname())){
	                    loginInfo = engine.sinaWeiboLoginSSO(SettingLoginActivity.this,db.getToken(), db.getExpiresIn(), db.getUserId(), "192.168.1.100", db.getExpiresTime(),db.getUserName(),db.getUserIcon());
	                }/*else if(TencentWeibo.NAME.equals(db.getPlatformNname())){
	                    loginInfo = engine.tencentWeiboLoginSSO(SettingLoginActivity.this,db.getToken(), db.getExpiresIn(), db.getUserId(), "192.168.1.100", db.getExpiresTime(),db.getUserName(),db.getUserIcon());
	                }*/else if(QQ.NAME.equals(db.getPlatformNname())){                	
	                	Logger.i(TAG, "db.getToken()="+db.getToken()+";db.getExpiresIn()="+db.getExpiresIn()+";db.getUserId()="+db.getUserId()+";db.getExpiresTime()="+db.getExpiresTime()+";db.getUserName()="+db.getUserName()
	                			+"db.getUserIcon()="+db.getUserIcon());
	                    loginInfo = engine.QQHuLianLoginSSO(SettingLoginActivity.this,db.getToken(), db.getExpiresIn(), db.getUserId(), "192.168.1.100", db.getExpiresTime(),db.getUserName(),db.getUserIcon());
	                }
	                else if(Wechat.NAME.equals(db.getPlatformNname())){
	                	Logger.i(TAG, "db.getToken()="+db.getToken()+";db.getExpiresIn()="+db.getExpiresIn()+";db.getUserId()="+db.getUserId()+";db.getExpiresTime()="+db.getExpiresTime()+";db.getUserName()="+db.getUserName());
	                    loginInfo = engine.wechatLoginSSO(SettingLoginActivity.this,db.getToken(), db.getExpiresIn(), db.getUserId(), "192.168.1.100", db.getExpiresTime(),db.getUserName(),db.getUserIcon());
	                }
                }else if(type == Constant.SSO_LOGIN_WEIXIN){
                	
                	loginInfo = engine.wechatLoginSSO(SettingLoginActivity.this,weiXinInfo.getAccess_token(), weiXinInfo.getExpires_in(),
                			weiXinInfo.getOpenid(), "192.168.1.100", weiXinInfo.getExpires_in(),"1","1");
				} else if (type == Constant.SSO_LOGIN_HUAWEI) {
					SimpleDateFormat format = new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss");
					String dateStr = format.format(new Date());
					loginInfo = engine.HuaWeiLoginSSO(
							SettingLoginActivity.this,
							mHuaWeiInfo.getAccesstoken(), System.currentTimeMillis()+"",
							mHuaWeiInfo.getUserID(), "192.168.1.100", dateStr,
							mHuaWeiInfo.getUserName(), "http://static.v1.cn/images/v1cn/user/touxiang-2.jpg");
				}
            } catch (ServicesException e) {
                e.printStackTrace();
                errorMsg = e.getMessage();
            }
            return null;
            
        }
        
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if(pd != null && pd.isShowing()){
                pd.cancel();
            }
            if (TextUtils.isEmpty(errorMsg) && loginInfo != null) {
                if(loginInfo.getCode() != null && loginInfo.getCode().equals(Constant.RESULT_CODE_SUCCESS_V1)){
                    loginInfo.saveInstance(SettingLoginActivity.this);
                    if(loginInfo.getUserImg().contains("jpg") || loginInfo.getUserImg().contains("png")){                    	
                    }else{
                    	List<BindInfo> bangdinglist = loginInfo.getBangdinglist();
                    	if(bangdinglist != null && bangdinglist.size() > 0){
                    		BindInfo bindInfo = bangdinglist.get(0);
                    		if(bindInfo != null && bindInfo.getAvatar_path().length() > 6){
                    			loginInfo.setUserImg(bindInfo.getAvatar_path());
                    			loginInfo.saveInstance(SettingLoginActivity.this);
                    			//更新服务器
//                    			new SendHeadToServerAsync(
//										LoginInfo.getInstance().getUserId(),
//										bindInfo.getAvatar_path())
//										.execute();
                    		}
                    	}
                    }
                    jumpTo();
                }else{
                	if(plat != null){
                		plat.removeAccount();
                    }
                	ToastAlone.showToast(SettingLoginActivity.this, loginInfo.getMsg(), 1);
                }
            } else {
                ToastAlone.showToast(SettingLoginActivity.this, errorMsg, 1);
            }
        }
    }
    
    /**
	 * 传送头像数据给服务器
	 */
	private class SendHeadToServerAsync extends AsyncTask<Void, Void, Boolean> {

		private String errorMsg = "";

		private ProgressDialog pd;
		int result = -1;
		String userId = "";
		String headUrl = "";

		public SendHeadToServerAsync(String userId, String headUrl) {
			this.userId = userId;
			this.headUrl = headUrl;
			// Logger.i(TAG, "SendHeadToServerAsync执行了……。");
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pd = Utils.getProgressDialog(SettingLoginActivity.this,
					getResources().getString(R.string.get_data), this);
			pd.show();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				NetEngine engine = new NetEngine();
				result = engine.SendHeadToServer(userId, headUrl);
			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = e.getMessage();
			}
			return false;

		}

		@Override
		protected void onPostExecute(Boolean resultBool) {
			super.onPostExecute(resultBool);
			if (pd != null && pd.isShowing()) {
				pd.cancel();
			}
			if (errorMsg == null) {
				if (result == 0) {
					// Logger.i("LoginInfo", "下面执行saveInstance方法");
					LoginInfo.getInstance().saveInstance(
							SettingLoginActivity.this);
				} else {
//					ToastAlone.showToast(SettingLoginActivity.this,
//							"上传头像失败，请稍后重试！", 1);
				}
				return;
			} else if (errorMsg.equals("")) {
//				if (result == 0) {
//					// Logger.i("LoginInfo", "下面执行1111saveInstance方法");
//					LoginInfo.getInstance().saveInstance(
//							SettingLoginActivity.this);
//				} else {
//					ToastAlone.showToast(SettingLoginActivity.this,
//							"上传头像失败，请稍后重试！", 1);
//				}
			} else {
//				ToastAlone.showToast(SettingLoginActivity.this, errorMsg, 1);
			}
		}
	}
	
    @Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		SettingLoginActivity.loginActivity = null;
	}

	@Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("登录页");
        MobclickAgent.onResume(this);
    }
    
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("登录页");
        MobclickAgent.onPause(this);
    }
    
    private class AsyncLoadStarUserInfo extends AsyncTask<Void, Void, Void> {

		String userInfo = "";
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			RequestEngine request = new RequestEngine();
			userInfo = request.getV1StarUserInfo();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(userInfo != null && userInfo.length() >= 1){
				if(handler != null){
					Message msg = handler.obtainMessage();
					msg.what = FINISH_LOAD_STAR_USERINFO;
					msg.obj = userInfo;
					handler.sendMessage(msg);
				}
			}
		}
		
	}
    private void getTheStarUserInfoToServer(String str){
		String url = V1VideoHttpApi.GET_STAR_USER_INFO_TO_SERVER() + "&devid=" + Constant.DEVICEID+"&uid="+LoginInfo.getInstance().getUserId()
				+"&keystr="+str;
		
		RequestManager.getInstance().getRequest(SettingLoginActivity.this, url,
				null, MainPageUploadEntity.class, 0, "MainPageNewActivity",
				new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String key) {
						// TODO Auto-generated method stub
						Logger.i(TAG, "onSuccess.object=" + object.toString());

						if (object != null) {}
					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						Logger.i("tag---onFailure", message);
					}

				});
	}
}
